package com.kingdee.jdy.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.jdy.util.HttpUtil;
import java.util.HashMap;
import java.util.Random;

/**
 * 商品
 */
public class MaterialController {


    public static long saveMaterial(HashMap<String, Object> urlParam, HashMap<String, Object> headerParam, long unitId)
        throws Exception {

        long materialid_id = 0;
        JSONObject jsonMaterial = prepareMaterialParam(unitId);
        JSONObject resMaterial = HttpUtil
            .doPost("http://api.kingdee.com/jdy/basedata/material_save", urlParam, headerParam, jsonMaterial.toJSONString());

        if (resMaterial != null) {
            JSONObject data = resMaterial.getJSONObject("data");
            if (data != null) {
                String success = data.getString("success");
                if (success.equalsIgnoreCase("true")) {
                    materialid_id = data.getJSONArray("successPkIds").getLongValue(0);
                    System.out.println("同步商品成功！materialid_id=" + materialid_id);
                } else {
                    System.out.println("同步商品失败！");
                }
            } else {
                System.out.println("同步商品失败！");
            }
        } else {
            System.out.println("同步商品失败！");
        }
        return materialid_id;
    }



    public static JSONObject prepareMaterialParam(long unitid){
        /*
{
	"id":null,
    "name":"测试新建商品",
    "baseunitid_id":"1",
    "purchaseunitid_id":"1",
    "saleunitid_id":"1",
    "storeunitid_id":"1",
    "auxunitid_id":"1",
    "priceentity":[{
    	"price_unitid_id":"1",
    	"price_retailprice":"1.2"
    }
    	]
}
         */
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", null);
        jsonObject.put("name", "demo测试商品" + new Random().nextInt());
        jsonObject.put("baseunitid_id", unitid);
        jsonObject.put("purchaseunitid_id", unitid);
        jsonObject.put("saleunitid_id", unitid);
        jsonObject.put("storeunitid_id", unitid);
        jsonObject.put("auxunitid_id", unitid);

        JSONArray priceentityArray = new JSONArray();
        JSONObject entity = new JSONObject();
        entity.put("price_unitid_id",unitid);
        entity.put("price_retailprice","1.2");
        priceentityArray.add(entity);

        jsonObject.put("priceentity", priceentityArray);

        return jsonObject;
    }



}
